package com.atguigu.spzx.user.service.Impl;

import com.atguigu.spyx.model.common.com.atguigu.spyx.model.entity.h5.UserAddress;
import com.atguigu.spzx.common.interceptor.SpzxUserInterceptor;
import com.atguigu.spzx.user.mapper.RegionMapper;
import com.atguigu.spzx.user.mapper.UserAddressMapper;
import com.atguigu.spzx.user.service.UserAddressService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author LT
 * @create 2023-11-21-18:09
 */
@Service
public class UserAddressServiceImpl implements UserAddressService {

    @Resource
    UserAddressMapper userAddressMapper;
    @Resource
    RegionMapper regionMapper;
    @Transactional(rollbackFor = Exception.class)
    @Override
    public UserAddress findUserAddressById(Long id) {

        return userAddressMapper.findUserAddressById(id);
    }

    @Override
    public List<UserAddress> findUserAddressList() {
        Long userId = SpzxUserInterceptor.THREAD_LOCAL.get().getId();

        return userAddressMapper.findUserAddressListByUserId(userId);
    }

    @Override
    public void save(UserAddress userAddress) {
        Long userId = SpzxUserInterceptor.THREAD_LOCAL.get().getId();
        if (userAddress.getIsDefault().intValue()==1){
            userAddressMapper.updateDefaultByUserId(0,userId);
        }
        String regionNames = regionMapper.findRegionNamesByCode(userAddress.getDistrictCode());
        userAddress.setFullAddress(regionNames+userAddress.getAddress());

        userAddress.setUserId(userId);
        userAddressMapper.save(userAddress);
    }
}
